package com.edu.demo.filter;

import cn.hutool.json.JSONUtil;
import com.alibaba.druid.sql.ast.statement.SQLUniqueConstraint;
import com.edu.demo.constant.SecurityConstant;
import com.edu.demo.entity.LoginUser;
import com.edu.demo.entity.Student;
import com.edu.demo.service.impl.TokenService;
import com.edu.demo.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @ClassName: JwtAuthenticationTokenFilter
 * @Description:
 * @Author: jxw
 * @Date: 2023-01-28
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private TokenService tokenService;


    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String requestURI = httpServletRequest.getRequestURI();
        if(SecurityConstant.url.contains(requestURI)) {}
        else{
            LoginUser loginUser;
            if(requestURI.startsWith("/static")||requestURI.startsWith("/favicon.ico")){
                loginUser = new LoginUser();
            }else {
                loginUser = tokenService.getLoginUser(httpServletRequest);
                if(!Objects.isNull(loginUser) && Objects.isNull( SecurityUtils.getAuthentication())) {
                    tokenService.verifyToken(loginUser);
                }
            }
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        }

        filterChain.doFilter(httpServletRequest, httpServletResponse);

    }
}
